package com.common.dao.base;


import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.Column;

import org.apache.ibatis.mapping.MappedStatement;

import com.common.annotation.Order;

import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;


public class PagingSelectProvider extends MapperTemplate {

    public PagingSelectProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    /**
     * 根据Example查询
     *
     * @param ms
     * @return
     */
    public String selectWhereClausePaging(MappedStatement ms) {
        Class<?> entityClass = getEntityClass(ms);
        //将返回值修改为实体类型
        setResultType(ms, entityClass);
        StringBuilder sql = new StringBuilder("SELECT ");
        //支持查询指定列
        sql.append(SqlHelper.exampleSelectColumns(entityClass));
        sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
        sql.append(SqlHelper.whereAllIfColumns(entityClass, isNotEmpty()));
        sql.append(entityOrderBy(entityClass));
        return sql.toString();
    }
    /**
     * example查询中的orderBy条件，会判断默认orderBy
     *
     * @return
     */
    public static String entityOrderBy(Class<?> entityClass) {
        //使用注解拼接
        //@Order(type="desc")
        //private String id;
        Field[] fields = entityClass.getDeclaredFields();
        String orderByClause = "";
        Map<String,String> orderByClauseList = new HashMap<>();
        if(fields != null){
            for(Field field : fields){
                //是否有注解@Order
                if(field.isAnnotationPresent(Order.class)){
                    Order order = field.getAnnotation(Order.class);
                    if(order.type() != null){
                        //使用@Column标注获取属性名
                        Column column = field.getAnnotation(Column.class);
                        if(column != null){
                            orderByClauseList.put(column.name(),order.type());
                        }else{
                            orderByClauseList.put(field.getName(),order.type());
                        }
                    }
                }
            }
        }
        StringBuilder sb= new StringBuilder(" order by ");
        int i=1;
        for(Map.Entry<String,String> entry: orderByClauseList.entrySet()){
            sb.append(entry.getKey()+" "+entry.getValue());
            if(i!=orderByClauseList.entrySet().size()){
                sb.append(", ");
                i++;
            }
        }
        return sb.toString();
    }
}
